import { Box } from "@mui/material";
import hashFileAysc from "./HashFile";
import fetchData from "../../utils/ApiFetch";
import sliceFileAsyc from "./SliceFile";
import ProgressPanel from "../ProgressPanel/ProgressPanel";
import UploadPanel from "../UploadPanel/UploadPanel";
import { useDispatch, useSelector } from "react-redux";
import { postUpload, updateUpload } from "../../app/features/progressSlice";
const apiUrl = process.env.REACT_APP_API_URL;

var total = 0;
var curr = 0;

async function chunkUpload(chunkId, fileName, chunkIdx, chunkSize,chunk, parentId, onUpdate) {
    const checkChunk = await fetchData(`${apiUrl}/file/checkChunk`, 'POST', {chunkId , fileName, chunkIdx, chunkSize});
    if (checkChunk.data.uploaded === false) {
        const resp = await fetchData(`${apiUrl}/file/chunkUpload`, 'POST', {chunkId , fileName, chunkIdx, chunkSize, chunk, parentId});
        curr += 1;
    } else {
        curr += 1;
    }
    onUpdate(curr, curr/total);
}

async function finishChunkUpload(chunkId, fileName, parentId) {
    const resp = await fetchData(`${apiUrl}/file/finishChunkUpload`, 'POST', {chunkId , fileName, parentId});
}

var uploadFileCount = 0;

function TestWorker() {
    const uploadList = useSelector(state => state.progressReducer.uploadList);
    const dispatch = useDispatch();
    function handleOnChange(e) {
        if (e.target.files.length > 0) {
            const currCount = uploadFileCount;
            uploadFileCount += 1;
            dispatch(postUpload({id:currCount, fileName: e.target.files[0].name, state: 0}));
            hashFileAysc(e.target.files[0]).then(({fileHash}) => {
                console.log(e.target.files[0]);
                console.log(`fileHash = ${fileHash}`)
                async function initUpload() {
                    let chunkSize = 4194304;
                    let chunks = Math.ceil(e.target.files[0].size / chunkSize);
                    total = chunks;
                    curr = 0;
                    console.log(total);
                    const resp = await fetchData(`${apiUrl}/file/initChunkUpload`, 'POST', {fileName: e.target.files[0].name, fileHash:fileHash,numChunk:chunks, parentId: 0});
                    dispatch(updateUpload({id:currCount, fileName: e.target.files[0].name, state: 1}));
                    function updateProgress(curr, progress) {
                        if (progress !== 1) {
                            dispatch(updateUpload({id:currCount, fileName: e.target.files[0].name, state: 1, progress:progress}));
                        } else {
                            dispatch(updateUpload({id:currCount, fileName: e.target.files[0].name, state: 2, progress:progress}));
                        }
                    }
                    
                    sliceFileAsyc(e.target.files[0], (data)=>{
                        chunkUpload(resp.data.chunkId, e.target.files[0].name, data.currentChunk, data.chunkSize,new Blob([data.chunk]), 0, updateProgress  )
                    },
                    (data) => {
                    }
                    );
                }
                initUpload();
                
            });
        }
    }

   return (
    <Box>
        <input id="testfile" onChange={handleOnChange} type="file"></input>
        <ProgressPanel>
            <UploadPanel uploadList={uploadList}/>
        </ProgressPanel>
    </Box>
   )
}


export default TestWorker;